//
//  PersonalDetailPageViewController.swift
//  FeastBooking
//
//  Created by Imon on 2017/10/2.
//  Copyright © 2017年 Imon. All rights reserved.
//

import UIKit
import RxSwift

class PersonalDetailPageViewController: UIViewController {
    
    fileprivate let activityView: UIActivityIndicatorView = {
        let view = UIActivityIndicatorView(activityIndicatorStyle: .gray)
        view.startAnimating()
        return view
    }()
    
    var userProfile: UserProfile?
    
    var userProfileVM: UserProfileViewModel?
    
    let disposeBag = DisposeBag()
    
    var hasEditedAvatar = false
    
    let avatarPH = UIImage(named: "placeholder")
    
    var timer: Timer = Timer()
    
    var token: String?
    
    var actionSheet: UIAlertController!
    
    var scrollView: UIScrollView?
    
    var logoutCompletion: (() -> Void)?
    
    let authManager = AuthManager.share
    
    var visualView: UIVisualEffectView?
    
    let statusMessage: UILabel = {
        let label = UILabel()
        label.textColor = proceededColor
        label.textAlignment = .left
        label.font = AppFont(size: 20)
        label.text = LanguageHelper.getString(key: "SAVING")
        return label
    }()
    
//    @IBOutlet weak var logoutButton: UIButton!
    
    let avatar: AvatarBar = {
        let ab = AvatarBar()
        return ab
    }()
    
    let username: PersonalInformBar = {
        let bar = PersonalInformBar()
        bar.titleLabel.text = LanguageHelper.getString(key: "USERN")
        bar.valueLabel.text = ""
        return bar
    }()
    
    let email: PersonalInformBar = {
        let bar = PersonalInformBar()
        bar.titleLabel.text = LanguageHelper.getString(key: "EM")
        bar.valueLabel.text = ""
        return bar
    }()
    
    let phone: PersonalInformBar = {
        let bar = PersonalInformBar()
        bar.titleLabel.text = LanguageHelper.getString(key: "PHONE")
        bar.valueLabel.text = ""
        return bar
    }()
    
    let changePWD: PersonMenu = {
        let menu = PersonMenu()
        menu.titleLabel.text = LanguageHelper.getString(key: "CHANGE_PW")
        menu.titleLabel.textColor = UIColor.lightGray
        return menu
    }()

    override func viewDidLoad() {
        super.viewDidLoad()
        self.view.backgroundColor = lightSaperatorColor
        self.navigationItem.title = LanguageHelper.getString(key: "PERSONAL_PROFILE")
        setBackBarItem()
        let rightBt = UIButton()
        rightBt.contentHorizontalAlignment = .right
        rightBt.setTitle(LanguageHelper.getString(key: "SUBMIT"), for: .normal)
        rightBt.setTitleColor(doneItemButtonColor, for: .normal)
        rightBt.addTarget(self, action: #selector(submit(_:)), for: .touchUpInside)
        rightBt.sizeToFit()
        self.navigationItem.rightBarButtonItem = UIBarButtonItem.init(customView: rightBt)
        
        scrollView = UIScrollView()
        scrollView?.frame = CGRect(x: 0, y: 0, width: self.view.bounds.width, height: self.view.bounds.height) // - logoutButton.frame.height)
        scrollView?.showsVerticalScrollIndicator = false
        scrollView?.showsHorizontalScrollIndicator = false
        scrollView?.isScrollEnabled = true
        scrollView?.alwaysBounceVertical = true
        scrollView?.autoresizingMask = UIViewAutoresizing.flexibleHeight
        
        if let profile = userProfile {
            if let avatarUrl = profile.avatar {
                let url = URL(string: avatarUrl)!
                avatar.avatar.kf.setImage(with: url, placeholder: self.avatarPH)
            }
            username.valueLabel.text = profile.username != nil ? profile.username! : ""
            email.valueLabel.text = profile.email != nil ? "\(profile.email!)" : ""
            phone.valueLabel.text = profile.phone != nil ? "\(profile.phone!)" : ""
        }
        avatar.frame = CGRect(x: 0, y: 0, width: self.view.bounds.width, height: avatarBarHeight)
        
        username.frame = CGRect(x: 0, y: avatarBarHeight, width: self.view.bounds.width, height: menuHeight)
        
        email.frame = CGRect(x: 0, y: avatarBarHeight + menuHeight, width: self.view.bounds.width, height: menuHeight)
        
        phone.frame = CGRect(x: 0, y: avatarBarHeight + menuHeight * 2, width: self.view.bounds.width, height: menuHeight)
        
        changePWD.frame = CGRect(x: 0, y: avatarBarHeight + menuHeight * 3, width: self.view.bounds.width, height: menuHeight)
        
//        logoutButton.backgroundColor = UIColor.white
//        logoutButton.addTarget(self, action: #selector(logout(_:)), for: .touchUpInside)
        
        self.scrollView?.addSubview(username)
        self.scrollView?.addSubview(email)
        self.scrollView?.addSubview(phone)
        self.scrollView?.addSubview(changePWD)
        self.scrollView?.addSubview(avatar)
        
        scrollView?.contentSize = CGSize(width: self.view.bounds.width, height: changePWD.frame.origin.y + changePWD.frame.height)
        self.view.addSubview(scrollView!)
        
        let emailTapGR = UITapGestureRecognizer()
        emailTapGR.addTarget(self, action: #selector(tapEmail(_:)))
        email.addGestureRecognizer(emailTapGR)
        
        let phoneTapGR = UITapGestureRecognizer()
        phoneTapGR.addTarget(self, action: #selector(tapPhone(_:)))
        phone.addGestureRecognizer(phoneTapGR)
        
        let passwdTapGR = UITapGestureRecognizer()
        passwdTapGR.addTarget(self, action: #selector(tapPasswd(_:)))
        changePWD.addGestureRecognizer(passwdTapGR)
        
        let avatarTapGR = UITapGestureRecognizer()
        avatarTapGR.addTarget(self, action: #selector(tapAvatar(_:)))
        avatar.addGestureRecognizer(avatarTapGR)
        
        setActionSheet()
        setVisualView()
        initVM()
    }
    
    func initVM() {
        let authManager = AuthManager.share
        if authManager.hasLogined() {
            if let token = authManager.getToken() as? String {
                userProfileVM = UserProfileViewModel(token: token)
            }
        }
    }
    
    func setActionSheet() {
        actionSheet = UIAlertController(title: nil, message: nil, preferredStyle: .actionSheet)
        actionSheet.addAction(UIAlertAction(title: LanguageHelper.getString(key: "CANCEL"), style: .cancel, handler: { _ in
            
        }))
        actionSheet.addAction(UIAlertAction(title: LanguageHelper.getString(key: "CHOOSE_FROM_LIBRARY"), style: .default, handler: { [unowned self] _ in
            let imagePickerController = UIImagePickerController()
            imagePickerController.sourceType = .photoLibrary
            imagePickerController.delegate = self
            self.present(imagePickerController, animated: true, completion: nil)
        }))
        actionSheet.addAction(UIAlertAction(title: LanguageHelper.getString(key: "TAKE_PHOTO"), style: .default, handler: { [unowned self] _ in
            if UIImagePickerController.isSourceTypeAvailable(.camera) {
                let imagePickerController = UIImagePickerController()
                imagePickerController.sourceType = .camera
                imagePickerController.delegate = self
                self.present(imagePickerController, animated: true, completion: nil)
            } else {
                self.showPromptView(message: LanguageHelper.getString(key: "CAMERO_DOWN"), confirmText: LanguageHelper.getString(key: "OK"))
            }
        }))
    }
    
    func setVisualView() {
        let effect = UIBlurEffect(style: .light)
        visualView = UIVisualEffectView(effect: effect)
        visualView?.frame = UIScreen.main.bounds
        
        activityView.center = CGPoint(x: visualView!.frame.width/2.0, y: visualView!.frame.height/2.0)
        visualView?.contentView.addSubview(activityView)
        visualView?.contentView.addSubview(self.statusMessage)
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    
    func submit(_ sender: UIBarButtonItem) {
        if hasEditedAvatar {
            if let vm = userProfileVM {
                showWaitView()
                vm.postAvatar(avatar: self.avatar.avatar.image!).subscribe(onNext: { [unowned self] response in
                    if let status = response.status {
                        if status != 200 {
                            self.operationFail(msg: "\(LanguageHelper.getString(key: "ERROR_OCCUR")) \(status)")
                        }
                    } else {
                        if let success = response.success {
                            if success {
                                self.operationSuccess()
                            } else {
                                if let data = response.data {
                                    self.operationFail(msg: data)
                                } else {
                                    self.operationFail(msg: LanguageHelper.getString(key: "ERROR_OCCUR"))
                                }
                            }
                        }
                    }
                    
                })
                .addDisposableTo(disposeBag)
            }
        } else {
            self.showPromptView(message: LanguageHelper.getString(key: "NOTHING_CHANGED"), confirmText: LanguageHelper.getString(key: "OK"))
        }
    }
    
//    func logout(_ sender: UIButton) {
//        let al = UIAlertController.init(title: nil, message: "確定要退出登錄嗎", preferredStyle: .alert)
//        let confirm = UIAlertAction.init(title: "確認", style: .destructive, handler: { [unowned self] _ in
//            self.logoutIM() //先登出IM服務器
//            self.authManager.logout()
//            SystemMessageDB.logoutInstance() //退出当前用户系统消息的数据库
//            RecentSearchDB.logoutInstance()  //退出当前用户最近搜索的数据库
//            if let completion = self.logoutCompletion {
//                completion()
//            }
//            self.navigationController?.popViewController(animated: true)
//        })
//        let cancel = UIAlertAction.init(title: "取消", style: .cancel, handler: nil)
//        al.addAction(confirm)
//        al.addAction(cancel)
//        self.present(al, animated: true, completion: nil)
//    }
//
//    func logoutIM() {
//        JMSGUser.logout({ (result, error) in
//            JCVerificationInfoDB.shareInstance.queue = nil
//            UserDefaults.standard.removeObject(forKey: kCurrentUserName)
//            UserDefaults.standard.removeObject(forKey: kCurrentUserPassword)
//        })
//    }
    
    func tapAvatar(_ sender: UIGestureRecognizer) {
        UIView.animate(withDuration: 0.3, animations: { [unowned self] in
            self.avatar.backgroundColor = UIColor.init(red: 200 / 255.0, green: 200 / 255.0, blue: 200 / 255.0, alpha: 0.5)
            }, completion: { [unowned self] bool in
                self.avatar.backgroundColor = UIColor.white
                self.present(self.actionSheet, animated: true, completion: nil)
        })
    }
    
    func tapEmail (_ sender: UIGestureRecognizer) {
        UIView.animate(withDuration: 0.3, animations: { [unowned self] in
            self.email.backgroundColor = UIColor.init(red: 200 / 255.0, green: 200 / 255.0, blue: 200 / 255.0, alpha: 0.5)
            }, completion: { [unowned self] bool in
                self.email.backgroundColor = UIColor.white
                let editPage = UIStoryboard(name: "Main", bundle: Bundle.main).instantiateViewController(withIdentifier: "PersonEditViewController") as! PersonEditViewController
                editPage.editType = .email
                editPage.completion = { [unowned self] in
                    self.navigationController?.popToRootViewController(animated: true)
                    self.showPromptView(message: LanguageHelper.getString(key: "OPERATION_SUCCESS"), confirmText: LanguageHelper.getString(key: "OK"))
                }
                self.navigationController?.pushViewController(editPage, animated: true)
        })
    }
    
    func tapPhone (_ sender: UIGestureRecognizer) {
        UIView.animate(withDuration: 0.3, animations: { [unowned self] in
            self.phone.backgroundColor = UIColor.init(red: 200 / 255.0, green: 200 / 255.0, blue: 200 / 255.0, alpha: 0.5)
            }, completion: { [unowned self] bool in
                self.phone.backgroundColor = UIColor.white
                let editPage = UIStoryboard(name: "Main", bundle: Bundle.main).instantiateViewController(withIdentifier: "PersonEditViewController") as! PersonEditViewController
                editPage.editType = .phone
                editPage.completion = { [unowned self] in
                    self.navigationController?.popToRootViewController(animated: true)
                    self.showPromptView(message: LanguageHelper.getString(key: "OPERATION_SUCCESS"), confirmText: LanguageHelper.getString(key: "OK"))
                }
                self.navigationController?.pushViewController(editPage, animated: true)
        })
    }
    
    func tapPasswd (_ sender: UIGestureRecognizer) {
        UIView.animate(withDuration: 0.3, animations: { [unowned self] in
            self.changePWD.backgroundColor = UIColor.init(red: 200 / 255.0, green: 200 / 255.0, blue: 200 / 255.0, alpha: 0.5)
            }, completion: { [unowned self] bool in
                self.changePWD.backgroundColor = UIColor.white
                let editPage = UIStoryboard(name: "Main", bundle: Bundle.main).instantiateViewController(withIdentifier: "PersonEditViewController") as! PersonEditViewController
                editPage.editType = .password
                editPage.completion = { [unowned self] in
                    self.navigationController?.popToRootViewController(animated: true)                    
                }
                self.navigationController?.pushViewController(editPage, animated: true)
        })
    }

    func showWaitView() {
        setMessage(message: LanguageHelper.getString(key: "SAVING"))
        self.navigationController?.setNavigationBarHidden(true, animated: true)
        self.view.addSubview(visualView!)
        self.activityView.startAnimating()
        timer = Foundation.Timer.scheduledTimer(timeInterval: 30, target: self, selector: #selector(timeout), userInfo: nil, repeats: false)
    }
    
    func operationSuccess() {
        timer.invalidate()
        setMessage(message: LanguageHelper.getString(key: "OPERATION_SUCCESS"))
        self.activityView.stopAnimating()
        DispatchQueue.main.asyncAfter(deadline: .now() + 2) {
            self.visualView?.removeFromSuperview()
            self.navigationController?.popViewController(animated: true)
        }
    }
    
    func operationFail(msg: String) {
        timer.invalidate()
        setMessage(message: msg)
        DispatchQueue.main.asyncAfter(deadline: .now() + 2) {
            self.activityView.stopAnimating()
            self.visualView?.removeFromSuperview()
            self.navigationController?.popViewController(animated: true)
        }
    }
    
    func timeout() {
        timer.invalidate()
        setMessage(message: LanguageHelper.getString(key: "TIMEOUT"))
        DispatchQueue.main.asyncAfter(deadline: .now() + 2) {
            self.activityView.stopAnimating()
            self.visualView?.removeFromSuperview()
            self.navigationController?.popViewController(animated: true)
        }
    }
    
    func setMessage(message: String) {
        statusMessage.text = message
        let maxSize = CGSize(width: self.view.bounds.width, height: 40)
        let messageSize = TextSize.textSize(text: statusMessage.text!, font: statusMessage.font, maxSize: maxSize)
        statusMessage.frame = CGRect(x: (self.view.bounds.width - messageSize.width) / 2, y: self.view.bounds.height / 2 - messageSize.height - 30, width: messageSize.width, height: messageSize.height)
    }
    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        // Get the new view controller using segue.destinationViewController.
        // Pass the selected object to the new view controller.
    }
    */

}

extension PersonalDetailPageViewController: UIImagePickerControllerDelegate, UINavigationControllerDelegate {
    
    func imagePickerControllerDidCancel(_ picker: UIImagePickerController) {
        dismiss(animated: true, completion: nil)
    }
    
    func imagePickerController(_ picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : Any]) {
        guard let selectedImage = info[UIImagePickerControllerOriginalImage] as?
            UIImage else {
                fatalError("Expected a dictionary containing an image, but was provided the following: \(info)")
        }
        self.avatar.avatar.image = selectedImage
        self.hasEditedAvatar = true
        dismiss(animated: true, completion: nil)
    }
}
